package com.summer.mall.controller.admin;

import com.summer.mall.common.Const;
import com.summer.mall.common.ResponseService;
import com.summer.mall.entity.User;
import com.summer.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/manage/user")
public class UserManageController {
    @Autowired
    private UserService userService;
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public ResponseService<User> login(@RequestParam String username,@RequestParam String password, HttpSession session){
        ResponseService<User> response = userService.login(username,password);

        if(response.isSuccess()){
            if(response.getData().getRole() == Const.Role.ROLE_ADMIN){
                session.setAttribute(Const.CURRENT_USER ,response.getData());
                return response;
            }else{
                return ResponseService.createByErrorMessage("不是管理员无法登录");
            }

        }
        return response;
    }

    @RequestMapping(value = "/logout",method = RequestMethod.POST)
    @ResponseBody
    public ResponseService<User> logout(HttpSession session){
        session.removeAttribute(Const.CURRENT_USER);
        return ResponseService.createBySuccess();
    }
}